<template>
  <div class="page-container movie-form">
    <el-form class="el-form-modify" ref="form" label-width="120px" :model="formData" :rules="rules">
      <div class="flex justify-between align-center">
        <h3 class="sub-title">基础信息</h3>
        <el-button size="small" type="primary" @click="showAttribute">属性管理</el-button>
      </div>
      
      <el-divider></el-divider>
      <div class="flex ">
        <el-form-item label="海报" prop="poster">
          <upload-image  :uploadUrl="uploadPostUrl" class="poster" v-model="formData.poster">

          </upload-image>
        </el-form-item>
        <div class="flex-sub">
          <el-form-item label="电影名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入电影名称" />
          </el-form-item>
          <el-form-item label="影片地区" prop="area">
            <el-input v-model="formData.area" placeholder="请输入影片地区" />
          </el-form-item>
          <el-form-item label="英文名" prop="englishName">
            <el-input v-model="formData.englishName" placeholder="请输入英文名" />
          </el-form-item>
          <el-form-item label="电影时长" prop="length">
            <el-input-number v-model="formData.length" :min="0" placeholder="请输入电影时长"></el-input-number>分钟
          </el-form-item>
        </div>
        <div class="flex-sub">
          <el-form-item label="电影类型" prop="types">
            <el-input v-model="formData.types" placeholder="请输入电影类型"></el-input>
          </el-form-item>
          <!-- <el-form-item label="电影类型" prop="types">
            <el-checkbox-group v-model="formData.types">
              <el-checkbox v-for="(type, index) in types" :key="index" :label="type"></el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
          <el-form-item label="电影制式" prop="formats">
            <el-checkbox-group v-model="formData.formats">
              <el-checkbox v-for="(format, index) in formats" :key="index" :label="format"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="剧情简介" prop="shortPlot">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8}"
          placeholder="请输入剧情简介"
          v-model="formData.shortPlot">
        </el-input>
      </el-form-item>
      <h3 class="sub-title credits-title">演职人员<el-button class="ml-10" type="primary" size="small" @click="addCreditsType">新增类型</el-button></h3>
      <el-divider></el-divider>
      <div>
        <el-form-item class="actor-form-item" label="导演" prop="directors">
          <el-row :gutter="10">
            <el-col class="mb-10" v-for="(director, index) in formData.directors" :key="index" :span="5" >
              <el-input  v-model="formData.directors[index]" placeholder="名字">
                <i
                    class="el-icon-remove-outline"
                    slot="suffix"
                    @click="delCredits('directors', index)">
                  </i>
              </el-input>
            </el-col>
            <el-col class="mb-10" :span="3">
              <i class="el-icon-circle-plus" @click="addCredits('directors')"></i>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="actor-form-item" label="演员" prop="actors">
          <el-row :gutter="10">
            <el-col class="mb-10" v-for="(actor, index) in formData.actors" :key="index" :span="5" >
              <el-input  v-model="formData.actors[index]"  placeholder="名字">
                <i
                    class="el-icon-remove-outline"
                    slot="suffix"
                    @click="delCredits('actors', index)">
                  </i>
              </el-input>
            </el-col>
            <el-col class="mb-10" :span="3">
              <i class="el-icon-circle-plus" @click="addCredits('actors')"></i>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="actor-form-item" label="编剧" prop="scenarists">
          <el-row :gutter="10">
            <el-col class="mb-10" v-for="(scenarist, index) in formData.scenarists" :key="index" :span="5" >
              <el-input  v-model="formData.scenarists[index]"  placeholder="名字">
                <i
                    class="el-icon-remove-outline"
                    slot="suffix"
                    @click="delCredits('scenarists', index)">
                  </i>
              </el-input>
            </el-col>
            <el-col class="mb-10" :span="3">
              <i class="el-icon-circle-plus" @click="addCredits('scenarists')"></i>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="actor-form-item" label="监制" prop="producers">
          <el-row :gutter="10">
            <el-col class="mb-10" v-for="(producer, index) in formData.producers" :key="index" :span="5" >
              <el-input  v-model="formData.producers[index]" placeholder="名字">
                <i
                    class="el-icon-remove-outline"
                    slot="suffix"
                    @click="delCredits('producers', index)">
                  </i>
              </el-input>
            </el-col>
            <el-col class="mb-10" :span="3">
              <i class="el-icon-circle-plus" @click="addCredits('producers')"></i>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item class="actor-form-item" v-for="(other, typeIndex) in formData.otherStaffs " :key="'typeIndex_' + typeIndex" 
          :prop="'otherStaffs[' + typeIndex + ']'" :rules="otherRules">
          <el-input slot="label" v-model="other.name" placeholder="类型">
            <i
              class="el-icon-remove-outline"
              slot="suffix"
              @click="delCreditsType(typeIndex)">
            </i>
          </el-input>
          <el-row :gutter="10">
            <el-col class="mb-10" v-for="(val, index) in other.values" :key="index" :span="5" >
              <el-input  v-model="other.values[index]" placeholder="名字">
                <i
                    class="el-icon-remove-outline"
                    slot="suffix"
                    @click="delOtherCredits(typeIndex, index)">
                  </i>
              </el-input>
            </el-col>
            <el-col class="mb-10" :span="3">
              <i class="el-icon-circle-plus" @click="addOtherCredits(typeIndex)"></i>
            </el-col>
          </el-row>
        </el-form-item>
      </div>
      <div class="text-center mb-40">
        <el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
        <el-button @click="cancel" size="small">取消</el-button>
      </div>
    </el-form>
    <attribute-dialog ref="attributeDialog" :movieId="movieId"  :tags="tags" @change="tags => this.tags = tags"></attribute-dialog>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage1';
import {posterPathPrefix} from '@/settings';
import {movieDetial, movieFormats, movieEdit, movieTypes, uploadPostUrl} from '@/api/viewing';
import {rules} from '@/utils/validate';
import AttributeDialog from './AttributeDialog';

export default {
  name: 'EquityForm',
  components: {
    uploadImage: UploadImage,
    attributeDialog: AttributeDialog
  },
  data() {
    let validateCredits = (rule, value, callback) => {
      if (value.length == 0) {
        return callback(new Error('必须添加一项'));
      }

      for(let index = 0; index < value.length; index++ ) {
        if (!value[index].trim()) {
          return callback(new Error('名字不能有空'));
        }
      }
      callback();
    };

    let validateOtherCredits = (rule, value, callback) => {
      let err = '';
      if (!value.name) {
        err += '类型名不能为空;';
      }

      for(let index = 0; index < value.values.length; index++ ) {
        if (!value.values[index].trim()) {
          err += '名字不能有空';
          break;
        }
      }

      if (err != '') {
        callback(new Error(err));
      }

      callback();
    };

    return {
      movieId: this.$route.params.movieId || '',
      pathPrefix: posterPathPrefix,
      uploadPostUrl,
      formData: {
        poster: '', // 海报路劲
        name: '', // 中文名
        area: '', // 放映类型
        englishName: '', // 英文名
        length: '', // 片长
        // types: [], // 电影类型
        types: '', // 电影类型
        // dimensional: '', // 影片放映类型
        formats: [], // 电影制式
        shortPlot: '', // 剧情简介
        directors: [], // 导演了列表
        actors: [], // 演员列表
        scenarists: [], // 编剧列表
        producers: [], // 监制列表
        otherStaffs: [], // 其它演职人员列表，先用数组存储，提交时改成对象
      },
      rules: {
        poster: [rules.required],
        name: [rules.required],
        area: [rules.required],
        englishName: [rules.required],
        length: [rules.required],
        // types: [rules.array_required],
        types: [rules.required],
        formats: [rules.array_required],
        shortPlot: [rules.required],
        directors: [{type: 'array', required: true, message: '必须添加一项'}, {validator: validateCredits}],
        actors: [{type: 'array', required: true, message: '必须添加一项'}, { validator: validateCredits}],
        scenarists: [{type: 'array', required: true, message: '必须添加一项'}, {validator: validateCredits}],
        producers: [{type: 'array', required: true, message: '必须添加一项'}, {validator: validateCredits}],
      },
      otherRules: [{validator: validateOtherCredits}],
      saving: false,
      formats: [],
      types: [],
      tags: [], // 属性
    }
  },
  methods: {
    addCreditsType(){
      this.formData.otherStaffs.push({
        name: '',
        values: ['']
      });
    },
    addCredits(type) {
      this.formData[type].push('');
      this.$refs.form.validateField(type);
    },
    delCredits(type, index) {
      this.formData[type].splice(index, 1);
      this.$refs.form.validateField(type);
    },
    delCreditsType(typeIndex) {
      this.formData.otherStaffs.splice(typeIndex, 1);
    },
    addOtherCredits(typeIndex)  {
      this.formData.otherStaffs[typeIndex].values.push('');
      this.$refs.form.validateField(`otherStaffs[${typeIndex}]`);
    },
    delOtherCredits(typeIndex, index) {
      this.formData.otherStaffs[typeIndex].values.splice(index, 1);
    },
    async requestDetail(movieId) {
      try {
        const {data} = await movieDetial(movieId)
        if (data) {
          let {directors, actors, scenarists, producers, otherStaffs, formats, types, tags} = data;

          // types = types ? types.split(';')  : [];
          formats = formats ? formats.split(';')  : [];

          directors = directors ? directors.split(';') : [''];
          actors = actors ? actors.split(';') : [''];
          scenarists = scenarists? scenarists.split(';') : [''];
          producers = producers? producers.split(';') : [''];
          otherStaffs = JSON.parse(otherStaffs || '{}');
          otherStaffs = Object.keys(otherStaffs).map(other => {
            return {
              name: other,
              values: otherStaffs[other]
            }
          })
          this.tags = tags ? tags.split(';') : [];
          Object.assign(this.formData, {...data, directors, actors, scenarists, producers, otherStaffs, types, formats});
        } else {
          this.cancel();
        }
      } catch(err) {
        console.log(err)
        this.cancel();
      }
    },
    async movieFormats() {
      const {data} = await movieFormats();
      this.formats = data;
    },
    async movieTypes() {
      const {data} = await movieTypes();
      this.types = data;
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        console.log(valid);

        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          let postData = {...this.formData},
            otherStaffs = postData.otherStaffs;
          postData.otherStaffs = {};
          
          otherStaffs.forEach(item => {
            postData.otherStaffs[item.name] = item.values
          });

          postData.types = [postData.types];
          
          await movieEdit(postData.id, postData);
          this.saving = false;
          this.$message.success('保存成功!');
          this.$emit('refresh');
          this.cancel();
        } catch(err) {
          this.saving = false;
        }
      })
    },
    cancel() {
      this.$router.go(-1);
    },
    showAttribute() {
      this.$refs.attributeDialog.show();
    }
  },
  created() {
    let {movieId} = this.$route.params;
    if (movieId) {
      this.movieTypes();
      this.movieFormats();
      this.requestDetail(movieId);
    } else {
      this.cancel();
    }
  }
}
</script>

<style lang="scss">
.page-container.movie-form{
  margin: 0;

  .sub-title{
    margin: 0;
  }

  .el-form-modify{
    width: auto;
  }

  .credits-title{
    margin: 40px 0 10px 0;
  }

  .el-icon-remove-outline{
    font-size: 18px;
     color: #F56C6C;
  }

  .el-icon-circle-plus{
    font-size: 18px;
    color: #409EFF;
  }

  .avatar-uploader{
    .avatar-uploader-icon,
    .avatar{
      width: 162px;
      height: 243px;
      line-height: 243px;
    }
  }

  .actor-form-item{
    display: flex;

    .el-form-item__label{
      float: none;
    }

    .el-form-item__content{
      flex: 1;
      margin-left: 0 !important;
    }
  }
}
</style>